// ==========================================================================
// 云捷GO自动生成控制器相关代码，只生成一次，按需修改,再次生成不会覆盖.
// 生成日期：2021-07-09 11:02:15
// 生成路径: app/controller/module/category/category_controller.go
// 生成人：gfcms
// ==========================================================================
package category

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gfile"
	"github.com/gogf/gf/text/gstr"
	tableColumnModel "myblog/app/model/tool/table_column"
	"os"
	"strconv"
	"strings"
	"time"
	"myblog/app/model"
	categoryModel "myblog/app/model/module/category"
	categoryService "myblog/app/service/module/category"
	userService "myblog/app/service/system/user"
	"myblog/app/utils/response"
)

//列表页
func List(r *ghttp.Request) {
	response.BuildTpl(r, "module/category/list.html").WriteTpl()
}

//列表分页数据
func ListAjax(r *ghttp.Request) {
	var req *categoryModel.SelectPageReq
	//获取参数
	if err := r.Parse(&req); err != nil {
		response.ErrorResp(r).SetMsg(err.Error()).Log("category管理", req).WriteJsonExit()
	}
	rows := make([]categoryModel.Entity, 0)
	result, err := categoryService.SelectListAll(req)

	if err == nil && len(result) > 0 {
		rows = result
	}
	r.Response.WriteJsonExit(rows)
}

//新增页面
func Add(r *ghttp.Request) {
	pid := r.GetQueryInt64("pid")
	var pmenu categoryModel.EntityExtend
	pmenu.Id = 0
	pmenu.Catname = "主目录"

	tmp, err := categoryService.SelectRecordById(pid)
	if err == nil && tmp != nil && tmp.Id > 0 {
		pmenu.Id = tmp.Id
		pmenu.Catname = tmp.Catname
	}
	//获取模板
	curDir, _ := os.Getwd()
	filepath, err := gfile.ScanDirFile(curDir+"/template/home", "*")
	var files []tableColumnModel.Files
	for k, v := range filepath {
		tem1 := gstr.SubStr(v, (strings.LastIndex(v, "\\") + 1))
		files = append(files, tableColumnModel.Files{
			Num:      k,
			Filename: tem1,
			Filepath: v,
		})
	}
	response.BuildTpl(r, "module/category/add.html").WriteTpl(g.Map{
		"menu":  pmenu,
		"files": files,
	})
}

//新增页面保存
func AddSave(r *ghttp.Request) {
	var req *categoryModel.AddReq
	//获取参数
	if err := r.Parse(&req); err != nil {
		response.ErrorResp(r).SetBtype(model.Buniss_Add).SetMsg(err.Error()).Log("category新增数据", req).WriteJsonExit()
	}
	///保存栏目图片
	if file := r.GetUploadFile("image"); file != nil {
		user := userService.GetProfile(r.Session)
		curDir, err := os.Getwd()
		if err != nil {
			response.ErrorResp(r).SetBtype(model.Buniss_Edit).SetMsg(err.Error()).Log("保存栏目图片", g.Map{"userid": user.UserId}).WriteJsonExit()
		}
		saveDir := curDir + "/public/upload/" //文件保存路径

		curdate := time.Now().UnixNano()
		file.Filename = strconv.FormatInt(curdate, 10) + ".png"
		name, err := file.Save(saveDir, true)
		if err != nil {
			r.Response.WriteExit(err)
		}
		req.Image = "/upload/" + name
	} else {
		req.Image = ""
	}
	id, err := categoryService.AddSave(req, r.Session)

	if err != nil || id <= 0 {
		response.ErrorResp(r).SetBtype(model.Buniss_Add).Log("category新增数据", req).WriteJsonExit()
	}
	response.SucessResp(r).SetData(id).Log("category新增数据", req).WriteJsonExit()
}

//修改页面
func Edit(r *ghttp.Request) {
	id := r.GetQueryInt64("id")

	if id <= 0 {
		response.ErrorTpl(r).WriteTpl(g.Map{
			"desc": "参数错误",
		})
		return
	}

	entity, err := categoryService.SelectRecordById(id)
	if err != nil || entity == nil {
		response.ErrorTpl(r).WriteTpl(g.Map{
			"desc": "数据不存在",
		})
		return
	}
	var pmenu categoryModel.EntityExtend
	pmenu.Id = 0
	pmenu.Catname = "主目录"
	tmp, err := categoryService.SelectRecordById(entity.Parentid)
	if err == nil && tmp != nil && tmp.Id > 0 {
		pmenu.Id = tmp.Id
		pmenu.Catname = tmp.Catname
	}
	//获取模板
	curDir, _ := os.Getwd()
	filepath, err := gfile.ScanDirFile(curDir+"/template/home", "*")
	var files []tableColumnModel.Files
	for k, v := range filepath {
		tem1 := gstr.SubStr(v, (strings.LastIndex(v, "\\") + 1))
		files = append(files, tableColumnModel.Files{
			Num:      k,
			Filename: tem1,
			Filepath: v,
		})
	}

	response.BuildTpl(r, "module/category/edit.html").WriteTpl(g.Map{
		"category": entity,
		"menu":     pmenu,
		"files":    files,
	})
}

//修改页面保存
func EditSave(r *ghttp.Request) {
	var req *categoryModel.EditReq
	//获取参数
	if err := r.Parse(&req); err != nil {
		response.ErrorResp(r).SetBtype(model.Buniss_Edit).SetMsg(err.Error()).Log("category修改数据", req).WriteJsonExit()
	}
	//保存栏目图片
	if file := r.GetUploadFile("image"); file != nil {
		user := userService.GetProfile(r.Session)
		curDir, err := os.Getwd()
		if err != nil {
			response.ErrorResp(r).SetBtype(model.Buniss_Edit).SetMsg(err.Error()).Log("保存栏目图片", g.Map{"userid": user.UserId}).WriteJsonExit()
		}
		saveDir := curDir + "/public/upload/" //文件保存路径

		curdate := time.Now().UnixNano()
		file.Filename = strconv.FormatInt(curdate, 10) + ".png"
		name, err := file.Save(saveDir, true)
		if err != nil {
			r.Response.WriteExit(err)
		}
		req.Image = "/upload/" + name
	} else {
		req.Image = req.Oldimage
	}
	//保存栏目图片结束
	rs, err := categoryService.EditSave(req, r.Session)

	if err != nil || rs <= 0 {
		response.ErrorResp(r).SetBtype(model.Buniss_Edit).Log("category修改数据", req).WriteJsonExit()
	}
	response.SucessResp(r).SetBtype(model.Buniss_Edit).Log("category修改数据", req).WriteJsonExit()
}

//删除数据
func Remove(r *ghttp.Request) {
	var req *model.RemoveReq
	//获取参数
	if err := r.Parse(&req); err != nil {
		response.ErrorResp(r).SetBtype(model.Buniss_Del).SetMsg(err.Error()).Log("category删除数据", req).WriteJsonExit()
	}

	rs := categoryService.DeleteRecordByIds(req.Ids)

	if rs > 0 {
		response.SucessResp(r).SetBtype(model.Buniss_Del).Log("category删除数据", req).WriteJsonExit()
	} else {
		response.ErrorResp(r).SetBtype(model.Buniss_Del).Log("category删除数据", req).WriteJsonExit()
	}
}

//导出
func Export(r *ghttp.Request) {
	var req *categoryModel.SelectPageReq
	//获取参数
	if err := r.Parse(&req); err != nil {
		response.ErrorResp(r).Log("category导出数据", req).WriteJsonExit()
	}
	url, err := categoryService.Export(req)

	if err != nil {
		response.ErrorResp(r).SetBtype(model.Buniss_Other).Log("category导出数据", req).WriteJsonExit()
	}
	response.SucessResp(r).SetBtype(model.Buniss_Other).SetMsg(url).WriteJsonExit()
}

//选择菜单树
func SelectMenuTree(r *ghttp.Request) {
	menuId := r.GetQueryInt64("menuId")
	var pmenu categoryModel.EntityExtend
	pmenu.Id = 0
	pmenu.Catname = "主目录"
	menu, _ := categoryService.SelectRecordById(menuId)
	if menu != nil {
		pmenu.Id = menu.Id
		pmenu.Catname = menu.Catname
	}
	response.BuildTpl(r, "module/category/tree.html").WriteTpl(g.Map{
		"menu": pmenu,
	})
}

////加载所有菜单列表树
func MenuTreeData(r *ghttp.Request) {

	ztrees, err := categoryService.MenuTreeData()
	if err != nil {
		response.ErrorResp(r).SetMsg(err.Error()).Log("栏目管理", g.Map{}).WriteJsonExit()
	}
	r.Response.WriteJsonExit(ztrees)
}
